package com.code.exception;

import com.alibaba.fastjson.JSON;
import com.code.constant.ErrorEnum;
import com.code.util.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常处理
 * 在Controller或者Service层有异常直接抛出 不需要try-catch 所有异常最终将在此类捕捉
 * @author CPZ
 * @create 2017-12-12
 **/
@Component
@Slf4j
public class ExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception exception) {
        log.error("ExceptionHandler: {1}", exception);

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        ResultData resultData = ResultData.error(ErrorEnum.ERROR);
        try {
            response.getWriter().write(JSON.toJSONString(resultData));
        } catch (IOException e) {
            log.error("", e);
        }
        return new ModelAndView();
    }
}
